package bb.lanxing.mvp.presetner;

import bb.lanxing.mvp.presetner.i.IPresenter;
import java.util.Iterator;
import java.util.LinkedList;
import rx.Subscription;

public abstract class BasePresenter implements IPresenter {
    private final LinkedList<Subscription> registerSubscriptions = new LinkedList<>();

    protected void addSubscription(Subscription subscription) {
        synchronized (this.registerSubscriptions) {
            this.registerSubscriptions.add(subscription);
        }
    }

    protected boolean removeSubscription(Subscription subscription) {
        boolean remove;
        synchronized (this.registerSubscriptions) {
            remove = this.registerSubscriptions.remove(subscription);
        }
        return remove;
    }

    protected boolean cancelSubscription(Subscription subscription) {
        if (!subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        return removeSubscription(subscription);
    }

    @Override
    public void destroy() {
        if (this.registerSubscriptions.isEmpty()) {
            return;
        }
        synchronized (this.registerSubscriptions) {
            Iterator<Subscription> it = this.registerSubscriptions.iterator();
            while (it.hasNext()) {
                Subscription next = it.next();
                if (!next.isUnsubscribed()) {
                    next.unsubscribe();
                }
            }
            this.registerSubscriptions.clear();
        }
    }
}
